package com.hpe.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hpe.dao.*;
import com.hpe.pojo.*;
import com.hpe.service.ExamService;
import com.hpe.util.DownloadUtil;
import com.hpe.util.ResponseCode;
import com.hpe.util.ServerResponse;
import com.hpe.util.ToolUtil;
import com.hpe.vo.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;


/**
 * @Author:TangWenhao
 * @Description:
 * @Date:19:02 2017/9/25
 */
@Transactional
@Service
public class ExamServiceImpl implements ExamService {

    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private SClassMapper sClassMapper;
    @Autowired
    private QuestionsMapper questionMapper;
    @Autowired
    private BigQuestionMapper bigQuestionMapper;
    @Autowired
    private StudentInfoMapper studentInfoMapper;
    @Autowired
    private ScoreMapper scoreMapper;

    @Override
    public ServerResponse<Exam> selectByPrimaryKey(Integer id) {
        return ServerResponse.createBySuccess("查询成功", examMapper.selectByPrimaryKey(id));
    }

    @Override
    public ServerResponse<PageInfo> findListByStuId(int id, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PaperInfo> availablePapers = examMapper.findListByStuId(id);
        PageInfo pageInfo = new PageInfo(availablePapers);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * @description 获得所有班级
     * @author Fujt
     * @date 2017/10/12 16:33
     */
    @Override
    public ServerResponse<List<Course>> getCourse() {
        List<Course> courseList = courseMapper.getAllCourseOrderById();
        return ServerResponse.createBySuccess(courseList);
    }

    /**
     * @description 根据type获取班级
     * @author Fujt
     * @date 2017/10/12 16:34
     */
    @Override
    public ServerResponse<List<SClass>> getSClassByType(int type) {
        List<SClass> stuClassList = sClassMapper.getClassListByType(type);
        if (stuClassList.size() <= 0) {
            return ServerResponse.createByErrorMsg("该方向没有班级");
        }
        return ServerResponse.createBySuccess(stuClassList);
    }

    /**
     * @description 根据 exam ids 获取exam
     * @author Fujt
     * @date 2017/10/13 21:31
     */
    @Override
    public ServerResponse<List<Exam>> getExamByIds(String[] ids) {
        List<Exam> exams = examMapper.findExamByIds(ids);
        if (exams.size() <= 0) {
            return ServerResponse.createBySuccessMsg("没有考试");
        }
        return ServerResponse.createBySuccess(exams);
    }

    @Override
    public ServerResponse<PageInfo> findCourseAvgByEdu(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AverageVo> courseAvg = examMapper.findCourseAvgByEdu();
        PageInfo pageInfo = new PageInfo(courseAvg);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public void getExamAvg(int classId, int courseId) {
        List<Exam> resultExam = examMapper.getExamIdForCCId(classId, courseId);
        for (int i = 0; i < resultExam.size(); i++) {
            examMapper.updateExamAvg(resultExam.get(i).getId());
        }
    }

    @Override
    public ServerResponse<PageInfo> findAllExamByClassId(int classId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassExamVo> classAvg = examMapper.findAllExamByClassId(classId);
        PageInfo pageInfo = new PageInfo(classAvg);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * @Author:XuShengJie
     * @Description:出卷之后生成相关考试班级所有人的初始化值
     * @Date:19:35 2017/10/17
     */
    @Override
    public void initScoreAfterExam(Exam exam) {
        //获取需要考试的所有班级
        String[] classIds = exam.getClassids().split(",");
        Score score = new Score();
        score.setExamId(exam.getId());
        for (String c : classIds) {
            // 获取每个班级的所有人
            List<Integer> studentid = studentInfoMapper.getAllStudentForClassId(Integer.valueOf(c));
            for (int i = 0; i < studentid.size(); i++) {
                score.setsId(studentid.get(i));
                score.setClassId(Integer.valueOf(c));
                score.setCreatedate(new Date());
                score.setContenttitl("@@@");
                score.setContentans("@@@");
                scoreMapper.insertSelective(score);
            }
        }
    }

    /**
     * @Author:XuShengJie
     * @Description:补考组卷
     * @Date:10:36 2017/10/24
     */
    @Override
    public ServerResponse<Map<String, Object>> addResetExam(ResetExamInfoVo resetExamInfoVo) {
        // 根据获取的课程id和题目个数，从题库中随机出题。
        //选择题
        List<Questions> list = questionMapper.findQuestionByCourseId(Integer.valueOf(resetExamInfoVo.getCourseId()));
        // 随机，重新洗牌。通过集合类里的方法。suffer
        Collections.shuffle(list);

        // 洗牌之后的数据集合中，获取num个数的题目。
        if (list.size() < resetExamInfoVo.getQuestionnum()) {// 题库数量不足。
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ERROR.getCode(), "选择题题库不足");
        }

        List questionList = new ArrayList();// 返回的选择题题库
        for (int i = 0; i < resetExamInfoVo.getQuestionnum(); i++) {
            list.get(i).setChoicea(HtmlUtils.htmlEscape(list.get(i).getChoicea()));
            list.get(i).setChoiceb(HtmlUtils.htmlEscape(list.get(i).getChoiceb()));
            list.get(i).setChoicec(HtmlUtils.htmlEscape(list.get(i).getChoicec()));
            list.get(i).setChoiced(HtmlUtils.htmlEscape(list.get(i).getChoiced()));
            questionList.add(list.get(i));
        }


        //简答题
        List<BigQuestion> list1 = bigQuestionMapper.findQuestionByTypeCid(Integer.valueOf(resetExamInfoVo.getCourseId()), 1);
        // 随机，重新洗牌。通过集合类里的方法。suffer
        Collections.shuffle(list1);

        // 洗牌之后的数据集合中，获取num个数的题目。
        if (list1.size() < resetExamInfoVo.getBqt1num()) {// 题库数量不足。
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ERROR.getCode(), "简答题题库不足");
        }

        List bigQuestionType1List = new ArrayList();// 返回的简答题题库
        for (int i = 0; i < resetExamInfoVo.getBqt1num(); i++) {
            bigQuestionType1List.add(list1.get(i));
        }


        //程序题
        List<BigQuestion> list2 = bigQuestionMapper.findQuestionByTypeCid(Integer.valueOf(resetExamInfoVo.getCourseId()), 2);
        // 随机，重新洗牌。通过集合类里的方法。suffer
        Collections.shuffle(list2);

        // 洗牌之后的数据集合中，获取num个数的题目。
        if (list2.size() < resetExamInfoVo.getBqt2num()) {// 题库数量不足。
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ERROR.getCode(), "程序题题库不足");
        }

        List bigQuestionType2List = new ArrayList();// 返回的编程题库
        for (int i = 0; i < resetExamInfoVo.getBqt2num(); i++) {
            bigQuestionType2List.add(list2.get(i));
        }

        //把时间转换成字符串
        Date currentTime = resetExamInfoVo.getStatrTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = formatter.format(currentTime);

        Course course = courseMapper.selectByPrimaryKey(Integer.valueOf(resetExamInfoVo.getCourseId()));
        //总分
        resetExamInfoVo.setScores(resetExamInfoVo.getScore1() + resetExamInfoVo.getScore2() + resetExamInfoVo.getScore3());
        Map<String, Object> examMap = new HashMap<>();
        examMap.put("question", questionList);
        examMap.put("bigt1Question", bigQuestionType1List);
        examMap.put("bigt2Question", bigQuestionType2List);
        examMap.put("exam", resetExamInfoVo);
        examMap.put("course", course);
        examMap.put("classid", resetExamInfoVo.getClassId());
        examMap.put("startTime", startTime);
        return ServerResponse.createBySuccess("组题成功", examMap);
    }

    /**
     * @Author:XuShengJie
     * @Description:生成补考答卷
     * @Date:16:21 2017/10/24
     */
    @Override
    public void initScoreAfterResetExam(Exam exam, String[] classId, String[] stuId) {
        //获取需要考试的所有班级
        Score score = new Score();
        score.setExamId(exam.getId());
        for (int i = 0; i < classId.length; i++) {
            score.setsId(Integer.valueOf(stuId[i]));
            score.setClassId(Integer.valueOf(classId[i]));
            score.setCreatedate(new Date());
            score.setContenttitl("@@@");
            score.setContentans("@@@");
            scoreMapper.insertSelective(score);
        }
    }

    @Override
    public void findExamByClassId(int classId,int stuId) {
        List<Exam> examList=examMapper.findExamByClassId(classId);
        String[] classIds={String.valueOf(classId)};
        String[] stuIds={String.valueOf(stuId)};
        for (Exam exam:examList){
            initScoreAfterResetExam(exam,classIds,stuIds);
        }
    }

    /* @description 获得所有的考试
    * @author Fujt
    * @date 2017/10/23 18:51
    */
    @Override
    public ServerResponse<PageInfo> findAllExam(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<ExamVo> examVos = examMapper.findAllExam();
        if (examVos.size() <= 0) {
            return ServerResponse.createByErrorMsg("暂时没有考试");
        }
        PageInfo pageInfo = new PageInfo(examVos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * @description 批量导出pdf => zip
     * @author Fujt
     * @date 2017/10/27 9:26
     */
    @Override
    public ServerResponse exportPdf(HttpServletRequest request, HttpServletResponse response, int examId) throws IOException, DocumentException {

        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        Font font = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK);
        Font fontBold = new Font(bfChinese, 12, Font.BOLD, BaseColor.BLACK);
        Font fontHead = new Font(bfChinese, 18, Font.BOLD, BaseColor.BLACK);
        Font fontExam = new Font(bfChinese, 22, Font.BOLD, BaseColor.BLACK);

        Exam exam = examMapper.selectByPrimaryKey(examId);

        List<String> schools = studentInfoMapper.findAllSchool();
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
        for (String school : schools) {
            List<StudentInfo> studentInfos = studentInfoMapper.findBySchoolName(school);
            for (StudentInfo studentInfo : studentInfos) {
                Score score = scoreMapper.selectByPrimaryKey(new ScoreKey(studentInfo.getId(), examId));
                if (score == null) {
                    continue;
                } else {
                    //zip中每个文件
                    ZipEntry zipEntry = new ZipEntry(school + "/" + studentInfo.getCollege() + "/" + studentInfo.getSchoolId() + "-" + studentInfo.getName() + ".pdf");
                    //相同人不能添加创建两个pdf   正常情况可忽略
                    try {
                        zipOutputStream.putNextEntry(zipEntry);
                    } catch (ZipException e) {
                        continue;
                    }
                    Document document = new Document();

                    document.setMargins(20, 20, 20, 20);

                    PdfWriter pdfWriter = PdfWriter.getInstance(document, zipOutputStream);
                    pdfWriter.setCloseStream(false);
                    document.open();
                    //设置水印
//                PdfContentByte pdfContentByte = pdfWriter.getDirectContent();
//                pdfContentByte.saveState();
//                PdfGState pdfGState = new PdfGState();
//                pdfGState.setFillOpacity(1.f);
//                pdfContentByte.setGState(pdfGState);
//                pdfContentByte.restoreState();
//                pdfContentByte.beginText();
//                BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI,
//                        BaseFont.EMBEDDED);
//                pdfContentByte.setFontAndSize(baseFont, 180);
//                pdfContentByte.setTextMatrix(30, 30);
//                pdfContentByte.showTextAligned(Element.ALIGN_LEFT, "HPE", 230, 430, 45);
//                pdfContentByte.endText();


                    //拆分简答题和编程题
                    String[] contentAns;
                    String[] shortAnses;
                    String[] programmingAnses;
                    String shortAns = "";
                    String programmingAns = "";
                    if (!"@@@".equals(score.getContentans())) {
                        contentAns = score.getContentans().split("@@@");
                        shortAnses = contentAns[0].split("~");// 简答题
                        programmingAnses = contentAns[1].split("~");// 编程题
                        for (int l = 0; l < programmingAnses.length; l++) {
                            programmingAns = programmingAns + "第" + (l + 1) + "小题：\n" + programmingAnses[l] + "\n";
                        }
                        for (int l = 0; l < shortAnses.length; l++) {
                            shortAns = shortAns + "第" + (l + 1) + "小题：\n" + shortAnses[l] + "\n";
                        }
                    } else {
                        shortAns = "未作答";
                        programmingAns = "未作答";
                    }

                    Paragraph p = new Paragraph("试卷："+exam.getName(), fontExam);
                    p.setAlignment(Element.ALIGN_CENTER);
                    document.add(p);
                    document.add(new Paragraph("\n"));

                    p = new Paragraph("答案及分数", fontHead);
                    p.setAlignment(Element.ALIGN_CENTER);
                    document.add(p);
                    document.add(new Paragraph("\n"));

                    //设置一个表格
                    PdfPTable pTable = new PdfPTable(8);

                    //答案表里填数据
                    PdfPCell[] pdfPCells = new PdfPCell[18];
                    // 学号
                    pdfPCells[0] = new PdfPCell(new Paragraph("学号: " + studentInfo.getSchoolId(), fontBold));
                    pdfPCells[0].setColspan(2);
                    // 姓名
                    pdfPCells[1] = new PdfPCell(new Paragraph("姓名: " + studentInfo.getName(), fontBold));
                    pdfPCells[1].setColspan(2);
                    // 院系
                    pdfPCells[2] = new PdfPCell(new Paragraph("院系: " + studentInfo.getCollege(), fontBold));
                    pdfPCells[2].setColspan(2);
                    // 专业
                    pdfPCells[3] = new PdfPCell(new Paragraph("专业: " + studentInfo.getMajor(), fontBold));
                    pdfPCells[3].setColspan(2);
                    // 选择题错题题号
                    pdfPCells[4] = new PdfPCell(new Paragraph("选择题错题题号：", fontBold));

                    //把选择题id转换为试卷中对应的题号
                    String question = exam.getQuestions();
                    if (question != null) {
                        String questions[] = question.substring(1, question.indexOf(";")).split(",");
                        String[] wrongQuestionId;
                        if (score.getWrongqueid() == null) {
                            wrongQuestionId = questions;
                        } else {
                            wrongQuestionId = score.getWrongqueid().split(",");
                        }
                        String trueQuestionId = "";

                        for (int i = 0; i < wrongQuestionId.length; i++) {
                            for (int j = 0; j < questions.length; j++) {
                                if (wrongQuestionId[i].trim().equals(questions[j].trim())) {
                                    if (trueQuestionId.length() == 0) {
                                        trueQuestionId += (j + 1);
                                        break;
                                    } else {
                                        trueQuestionId += "," + (j + 1);
                                        break;
                                    }
                                }
                            }
                        }
                        pdfPCells[5] = new PdfPCell(new Paragraph((trueQuestionId.equals("") ? "无" : trueQuestionId), font));
                        pdfPCells[5].setColspan(7);
                    } else {
                        pdfPCells[5] = new PdfPCell(new Paragraph("没有该类型题目", font));
                        pdfPCells[5].setColspan(7);
                        shortAns = "没有该类型题目";
                        programmingAns = "没有该类型题目";
                    }

                    String question1 = question.substring(question.indexOf(";")+2, question.indexOf(";", question.indexOf(";")+1));
                    if (question1.equals("")){
                        shortAns = "没有该类型题目";
                    }
                    String question2 = question.substring(question.indexOf(";", question.indexOf(";")+1)+2);
                    if (question2.equals("")) {
                        programmingAns = "没有该类型题目";
                    }

                    // 选择题分数
                    pdfPCells[6] = new PdfPCell(new Paragraph("选择题分数：", fontBold));

                    pdfPCells[7] = new PdfPCell(new Paragraph(String.valueOf(score.getScore1()), font));
                    pdfPCells[7].setColspan(7);
                    // 简答题答案
                    pdfPCells[8] = new PdfPCell(new Paragraph("简答题答案：", fontBold));
                    pdfPCells[9] = new PdfPCell(new Paragraph(shortAns, font));
                    pdfPCells[9].setColspan(7);
                    // 简答题分数
                    pdfPCells[10] = new PdfPCell(new Paragraph("简答题分数：", fontBold));

                    pdfPCells[11] = new PdfPCell(new Paragraph(String.valueOf(score.getScore2()), font));
                    pdfPCells[11].setColspan(7);
                    // 编程题答案
                    pdfPCells[12] = new PdfPCell(new Paragraph("编程题答案：", fontBold));
                    pdfPCells[13] = new PdfPCell(new Paragraph(programmingAns, font));
                    pdfPCells[13].setColspan(7);
                    // 编程题分数
                    pdfPCells[14] = new PdfPCell(new Paragraph("编程题分数：", fontBold));
                    pdfPCells[15] = new PdfPCell(new Paragraph(String.valueOf(score.getScore3()), font));
                    pdfPCells[15].setColspan(7);
                    // 总分数：
                    pdfPCells[16] = new PdfPCell(new Paragraph("总分数：", fontBold));
                    pdfPCells[17] = new PdfPCell(new Paragraph(String.valueOf(score.getScoreB()), font));
                    pdfPCells[17].setColspan(7);
                    for (int k = 0; k < pdfPCells.length; k++) {
                        pdfPCells[k].setPaddingTop(10f);
                        pdfPCells[k].setPaddingBottom(10f);
                        pTable.addCell(pdfPCells[k]);
                    }
                    //设置表格宽度百分比
                    pTable.setWidthPercentage(100);
                    //设置每列单元格宽度
                    float[] widths = {1.7f, 1f, 1f, 1f, 1f, 1f, 1f, 1f};
                    pTable.setWidths(widths);

                    document.add(pTable);
                    document.close();
                }

                zipOutputStream.closeEntry();
            }

        }

        DownloadUtil downloadUtil = new DownloadUtil();
        downloadUtil.download(zipOutputStream, response, request, exam.getName() + ".zip");
        zipOutputStream.close();


        return ServerResponse.createBySuccess();
    }


    @Override
    public ServerResponse<Map<String, Object>> readyAddExam(ExamInFo examInFo, String questions, Integer queType) {

        // 根据获取的课程id和题目个数，从题库中随机出题。
        //选择题
        List<Questions> list;
        if (questions != null) {
            //换题
            String[] qids = questions.split("@");
            if (qids[0] == null || "".equals(qids[0])) {
                //原组题中没有选择题
                list = questionMapper.findQuestionByCourseId(examInFo.getCourseid());
            } else {
                String[] qid = qids[0].split(",");
                list = questionMapper.findQuestionByCourseId2(examInFo.getCourseid(), qid);
            }
        } else {
            //正常组题
            list = questionMapper.findQuestionByCourseId(examInFo.getCourseid());
        }// 随机，重新洗牌。通过集合类里的方法。suffer
        Collections.shuffle(list);

        // 洗牌之后的数据集合中，获取num个数的题目。
        if (list.size() < examInFo.getQuestionNum() && (queType == -1 || queType == 0)) {// 题库数量不足。
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ERROR.getCode(), "选择题题库不足");
        }

        List questionList = new ArrayList();// 返回的选择题题库
        if (queType == -1 || queType == 0) {
            for (int i = 0; i < examInFo.getQuestionNum(); i++) {
                list.get(i).setChoicea(HtmlUtils.htmlEscape(list.get(i).getChoicea()));
                list.get(i).setChoiceb(HtmlUtils.htmlEscape(list.get(i).getChoiceb()));
                list.get(i).setChoicec(HtmlUtils.htmlEscape(list.get(i).getChoicec()));
                list.get(i).setChoiced(HtmlUtils.htmlEscape(list.get(i).getChoiced()));
                questionList.add(list.get(i));
            }
        }


        //简答题
        List<BigQuestion> list1;
        if (questions != null) {
            //换题
            String[] qids = questions.split("@");
            if (qids.length<2||qids[1] == null || "".equals(qids[1])) {
                list1 = bigQuestionMapper.findQuestionByTypeCid(examInFo.getCourseid(), 1);
            } else {
                String[] qid = qids[1].split(",");
                list1 = bigQuestionMapper.findQuestionByTypeCid2(examInFo.getCourseid(), 1, qid);
            }
        } else {
            //正常组题
            list1 = bigQuestionMapper.findQuestionByTypeCid(examInFo.getCourseid(), 1);
        }


        // 随机，重新洗牌。通过集合类里的方法。suffer
        Collections.shuffle(list1);

        // 洗牌之后的数据集合中，获取num个数的题目。
        if (list1.size() < examInFo.getBigQuestionType1Num() && (queType == -1 || queType == 1)) {// 题库数量不足。
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ERROR.getCode(), "简答题题库不足");
        }

        List bigQuestionType1List = new ArrayList();// 返回的简答题题库
        if (queType == -1 || queType == 1) {
            for (int i = 0; i < examInFo.getBigQuestionType1Num(); i++) {
                bigQuestionType1List.add(list1.get(i));
            }
        }


        //程序题
        List<BigQuestion> list2;
        if (questions != null) {
            //换题
            String[] qids = questions.split("@");
            if (qids.length == 2 || qids.length == 1) {
                //没出编程题的情况
                list2 = bigQuestionMapper.findQuestionByTypeCid(examInFo.getCourseid(), 2);
            } else {
                if (qids[2] == null || "".equals(qids[2])) {
                    list2 = bigQuestionMapper.findQuestionByTypeCid(examInFo.getCourseid(), 2);
                } else {
                    String[] qid = qids[2].split(",");
                    list2 = bigQuestionMapper.findQuestionByTypeCid2(examInFo.getCourseid(), 2, qid);
                }
            }
        } else {
            //正常组题
            list2 = bigQuestionMapper.findQuestionByTypeCid(examInFo.getCourseid(), 2);
        }
        // 随机，重新洗牌。通过集合类里的方法。suffer
        Collections.shuffle(list2);


        // 洗牌之后的数据集合中，获取num个数的题目。
        if (list2.size() < examInFo.getBigQuestionType2Num() && (queType == -1 || queType == 2)) {// 题库数量不足。
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ERROR.getCode(), "程序题题库不足");
        }

        List bigQuestionType2List = new ArrayList();// 返回的编程题库
        if (queType == -1 || queType == 2) {
            for (int i = 0; i < examInFo.getBigQuestionType2Num(); i++) {
                bigQuestionType2List.add(list2.get(i));
            }
        }

        //把时间转换成字符串
        Date currentTime = examInFo.getStarttime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = formatter.format(currentTime);

        Course course = courseMapper.selectByPrimaryKey(examInFo.getCourseid());
        //总分
        examInFo.setScores(examInFo.getScore() + examInFo.getScore1() + examInFo.getScore2());
        Map<String, Object> examMap = new HashMap<>();
        examMap.put("question", questionList);
        examMap.put("bigt1Question", bigQuestionType1List);
        examMap.put("bigt2Question", bigQuestionType2List);
        examMap.put("exam", examInFo);
        examMap.put("course", course);
        examMap.put("className", getSClassInFo(examInFo.getClassids()));
        examMap.put("classid", ToolUtil.arraytoString(examInFo.getClassids()));
        examMap.put("startTime", startTime);


        return ServerResponse.createBySuccess("组题成功", examMap);
    }

    /**
     * @Author:XuShengJie
     * @Description:发布试卷
     * @Date:9:36 2017/9/28
     */
    @Override
    public void addExam(Exam exam, Integer examId, String stuId) throws ParseException {
        //计算考试的结束时间
        long time = exam.getStarttime().getTime() + (long) (exam.getTesttime() * 1000 * 60);

        exam.setEndtime(new Date(time));
        //设置隐藏域存每类题的总分
        exam.setScores(exam.getScore1() + exam.getScore2() + exam.getScore());
        //正常考试
        if (examId == null) {
            examMapper.insertAndGetId(exam);
            //得到考试关联的所有学生的初始化成绩
            initScoreAfterExam(exam);
        } else {
            //补考重复班级去除
            String[] classId = exam.getClassids().split(",");
            ArrayList<String> list = new ArrayList();
            for (int i = 0; i < classId.length; i++) {
                //去除重复的班级
                if (!list.contains(classId[i])) {
                    list.add(classId[i]);
                }
            }
            //去除重复后的班级
            String[] classIds = list.toArray(new String[list.size()]);
            exam.setClassids(ToolUtil.arraytoString(classIds));
            exam.setId(examId);
            //出卷
            examMapper.insertAndGetId(exam);
            //生成补考答卷
            String[] studentId = stuId.split(",");
            initScoreAfterResetExam(exam, classId, studentId);
        }
    }

    @Override
    public ServerResponse<PageInfo> showMyCommitExam(int teacherId, int pageNum, int pageSize) {
        //获取分页信息
        PageHelper.startPage(pageNum, pageSize);
        //获取需要显示的所有试题
        List<ExamVo> commitedExam = examMapper.findExamVoByTeacherId(teacherId);
        //分页
        PageInfo pageInfo = new PageInfo(commitedExam);
        return ServerResponse.createBySuccess("获取曾经发布的试卷", pageInfo);
    }

    /**
     * @param classIds 所有的开发班级或者测试班级
     * @description 检索所有开发班级或者测试班级的考试
     * @author Fujt
     * @date 2017/10/12 15:31
     */
    @Override
    public ServerResponse<List<Exam>> getExamByClassIds(String classIds) {
        List<Exam> exams = examMapper.findExamByClassIds(classIds);
        if (exams.size() <= 0) {
            return ServerResponse.createByErrorMsg("没有符合条件的考试");
        }
        return ServerResponse.createBySuccess(exams);
    }

    /**
     * @Author:XuShengJie
     * @Description:根据班级Id数组获取考试班级名
     * @Date:19:01 2017/9/27
     */
    private String getSClassInFo(String[] ids) {
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < ids.length; i++) {
            //根据获取的id获取班级名
            SClass sclass = sClassMapper.selectByPrimaryKey(Integer.parseInt(ids[i]));
            str.append(sclass.getName());
            if (i < ids.length - 1) {
                str.append("-");
            }
        }
        return str.toString();
    }
}
